//
//  CompletionTableVC.m
//  Recycling
//
//  Created by jzd on 2018/5/19.
//  Copyright © 2018年 宋佳. All rights reserved.
//

#import "CompletionTableVC.h"
#import "CompletionCell.h"
#import "roteNavgationController.h"//导航
#import "orderDetailVC.h"//详情
#import "orderModel.h"

@interface CompletionTableVC ()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(assign,nonatomic)int page;
@property(strong,nonatomic)NSMutableArray *dataArray;
@property(assign,nonatomic)int total;
@end

@implementation CompletionTableVC

static NSString *const identify = @"CompletionCell";

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGBA(238.0, 238.0, 238.0, 1.0);
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(titleViewH+statsBarHeight+NavgationBarH, 0, self.tabBarController.tabBar.height, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CompletionCell class]) bundle:nil] forCellReuseIdentifier:identify];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    //位置被点击
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addressOnClick:) name:addressOnClickNotification object:nil];
    
    
    //完単的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestNewData) name:wandanNotification object:nil];
    
    self.tableView.mj_header = [SJRefresh headerWithRefreshingTarget:self refreshingAction:@selector(requestNewData)];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [SJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    
    
}
-(void)requestMoreData{
    self.page ++;
    //040001002：待接单
    //040001003：进行中
    //040001004：已完工
    
    NSDictionary *params = @{
                             @"pageno":@(self.page),
                             @"limit" : @(pageNum),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001004"
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            NSString *msg = [responseObject objectForKey:@"ErrorMessage"];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {

                    int total = [[data objectForKey:@"total"] intValue];
                    if (total<pageNum) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    NSArray *arr = [orderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"rows"]];
                    if (arr.count != 0) {
                        [self.dataArray addObjectsFromArray:arr];
                    }else{
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                        [self.navigationController.view showToast:@"没有更多数据" completion:nil];
                        return ;
                    }

                }else{
                    [self.navigationController.view showToast:@"暂无数据" completion:nil];
                }
            }else{
                [self.navigationController.view showToast:msg completion:nil];
            }
        }
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }];
}
-(void)requestNewData{
    self.page = 1;
    
    //040001002：待接单
    //040001003：进行中
    //040001004：已完工
    NSDictionary *params = @{
                             @"pageno":@(self.page),
                             @"limit" : @(pageNum),
                             @"wid":@([UserInfoTool shareUserInfoTool].Info.ID),
                             @"state":@"040001004"
                             };
    [[SJNetWorkTool sharedTool]requestWithURLString:getOrderList parameters:params method:GET callBack:^(id responseObject, NSError *error) {
        if (responseObject) {
            int code = [[responseObject objectForKey:@"Code"] intValue];
            NSString *msg = [responseObject objectForKey:@"ErrorMessage"];
            id data = [responseObject objectForKey:@"Data"];
            if (code == 1) {
                if (![data isKindOfClass:[NSNull class]]) {

                    int total = [[data objectForKey:@"total"] intValue];
                    self.total = total;
                    if (total<pageNum) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    NSArray *arr = [orderModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"rows"]];
                    if (arr.count != 0) {
                        self.dataArray = arr.mutableCopy;
                    }else{
                        [self.dataArray removeAllObjects];
                        [self.tableView.mj_header endRefreshing];
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                        [self.navigationController.view showToast:@"暂无数据" completion:nil];
                        return ;
                    }

                }else{
                    [self.dataArray removeAllObjects];
                    [self.navigationController.view showToast:@"暂无数据" completion:nil];
                }
            }else{
                [self.navigationController.view showToast:msg completion:nil];
            }
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer resetNoMoreData];
    }];
}
-(void)addressOnClick:(NSNotification *)noti{
    if ([noti.object isKindOfClass:[CompletionCell class]]) {
        CompletionCell *cell = noti.object;
        roteNavgationController *vc = [[roteNavgationController alloc]init];
        vc.goAddressStr = cell.model.UserAddress;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [[SJNetWorkTool sharedTool].tasks makeObjectsPerformSelector:@selector(cancel)];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    orderModel *model = [self.dataArray objectAtIndex:indexPath.row];
    CompletionCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 183;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    orderModel *model = [self.dataArray objectAtIndex:indexPath.row];
    orderDetailVC *vc = [[orderDetailVC alloc]init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    return [UIImage imageNamed:@"empty"];
    
}
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView {
    NSLog(@"空白页点击事件");
    //重新加载默认的数据
    [self.tableView.mj_header beginRefreshing];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *text = @"没有相关数据";
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:14.0f], NSForegroundColorAttributeName: TITLECOLOR};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView{
    
    NSString *text = @"重新加载";
    
    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new]; paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    
    paragraph.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0f], NSForegroundColorAttributeName: TITLECOLOR, NSParagraphStyleAttributeName: paragraph}; return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}
@end
